package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.common.AccessTokenFetcher;
import com.cmii.sjw.department.control.jsc.mapper.EduIndicatorsMapper;
import com.cmii.sjw.department.control.jsc.model.EduIndicators;
import com.cmii.sjw.department.control.jsc.model.KPIData;
import com.cmii.sjw.department.control.jsc.service.EduIndicatorsService;
import com.cmii.sjw.department.control.jsc.vo.EduIndicatorsVO;
import com.cmii.sjw.department.control.jsc.vo.KPIIndicator;
import com.cmii.sjw.department.control.jsc.vo.OtherIndicators;
import com.cmii.sjw.department.control.jsc.vo.OtherindicatorsVO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class EduIndicatorsServiceImpl extends ServiceImpl<EduIndicatorsMapper, EduIndicators> implements EduIndicatorsService {

    @Autowired
    private EduIndicatorsMapper eduIndicatorsMapper;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();


    // 接口URL列表
    private final String[] apiUrls = {
            "http://23.210.23.13:9000/edu-data-management/api/v1/broker/api/23",
    };

    /**
     * 教育指标明细
     *
     * @return 获取json数据
     */
    @Override
    public KPIData getData() {
        List<KPIIndicator> kpiIndicators = new ArrayList<>();
        List<OtherIndicators> otherIndicators = new ArrayList<>();

        for (String apiUrl : apiUrls) {
            try {
                List<EduIndicators> indicators = getValueFromApiWithTime(apiUrl);
                if (indicators != null && !indicators.isEmpty()) {
                    Map<String, List<EduIndicators>> categorizedMap = indicators.stream()
                            .collect(Collectors.groupingBy(EduIndicators::getPlateName));

                    for (Map.Entry<String, List<EduIndicators>> entry : categorizedMap.entrySet()) {
                        String platename = entry.getKey();
                        List<EduIndicators> platformIndicators = entry.getValue();

                        // 提取 KPI 指标
                        List<EduIndicatorsVO> kpiList = platformIndicators.stream()
                                .filter(EduIndicators::isKPI)
                                .map(indicator -> new EduIndicatorsVO()
                                        .setName(indicator.getName())
                                        .setCurValue(indicator.getCurValue()))
                                .collect(Collectors.toList());

                        // 提取其他指标
                        List<OtherindicatorsVO> otherList = platformIndicators.stream()
                                .filter(indicator -> !indicator.isKPI())
                                .map(indicator -> new OtherindicatorsVO()
                                        .setName(indicator.getName())
                                        .setCurValue(indicator.getCurValue()))
                                .collect(Collectors.toList());

                        if (!kpiList.isEmpty()) {
                            kpiIndicators.add(new KPIIndicator()
                                    .setPlatename(platename)
                                    .setKpiIndicators(kpiList));
                        }

                        if (!otherList.isEmpty()) {
                            otherIndicators.add(new OtherIndicators()
                                    .setPlatename(platename)
                                    .setOtherIndicators(otherList));
                        }
                    }
                }
            } catch (Exception e) {
                log.error("API调用失败: {}", e.getMessage(), e);
            }
        }

        return new KPIData(kpiIndicators, otherIndicators);
    }


    private List<EduIndicators> getValueFromApiWithTime(String baseUrl) {
        try {
            String accessToken = new AccessTokenFetcher().fetchAccessToken();
            log.info("使用的访问令牌: {}", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", accessToken);
            headers.setContentType(MediaType.APPLICATION_JSON);

            int page = 1;
            int pageSize = 10;
            List<EduIndicators> allIndicators = new ArrayList<>();

            while (true) {
                String url = baseUrl + "?page=" + page + "&pageSize=" + pageSize;
                HttpEntity<?> entity = new HttpEntity<>(headers);

                ResponseEntity<String> response = restTemplate.exchange(
                        url,
                        org.springframework.http.HttpMethod.GET,
                        entity,
                        String.class
                );

                if (response.getStatusCode().is2xxSuccessful()) {
                    String responseBody = response.getBody();
                    JsonNode jsonNode = objectMapper.readTree(responseBody);

                    JsonNode resultsNode = jsonNode.path("results");
                    if (resultsNode.isArray()) {
                        for (JsonNode resultNode : resultsNode) {

                            String name = resultNode.path("name").asText();
                            String curValue = resultNode.path("cur_value").asText();
                            if ("多跨事件".equals(name) && (curValue == null || curValue.isEmpty() || "null".equalsIgnoreCase(curValue))) {
                                curValue = "0";
                            }
                            EduIndicators indicator = new EduIndicators()
                                    .setDescription(resultNode.path("description").asText())
                                    .setDisplaySort(resultNode.path("display_sort").asText())
                                    .setDataType(resultNode.path("data_type").asText())
                                    .setId(resultNode.path("id").asInt())
                                    .setName(resultNode.path("name").asText())
                                    .setPlateId(resultNode.path("plate_id").asText())
                                    .setIsShow(resultNode.path("is_show").asInt())
                                    .setTargetValue(resultNode.path("target_value").asText())
                                    .setCurValue(curValue)
                                    .setPlateName(resultNode.path("plate_name").asText())
                                    .setKPI(
                                            "KPI".equals(name) ||
                                                    "体征指标".equals(name) ||
                                                    "多跨事件".equals(name));
                            ;

                            allIndicators.add(indicator);
                        }

                        int totalCount = jsonNode.path("totalCount").asInt();
                        if (allIndicators.size() >= totalCount) {
                            break;
                        }

                        page++;
                    } else {
                        log.error("响应中未找到有效的结果: {}", responseBody);
                        throw new RuntimeException("响应中未找到有效的结果");
                    }
                } else {
                    log.error("HTTP 请求返回: {} {}", url, response.getStatusCodeValue());
                    throw new RuntimeException("API 请求返回状态码异常");
                }
            }

            return allIndicators;
        } catch (Exception e) {
            log.error("API调用失败 {}: {}", baseUrl, e.getMessage(), e);
            throw new RuntimeException("API 调用失败", e);
        }
    }
}